package com.zhai.trigger.job;

import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import com.alibaba.fastjson.JSON;
import com.zhai.domain.task.model.entity.TaskEntity;
import com.zhai.domain.task.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: 发送消息定时任务
 * @ClassName: SendMessageTaskJob
 * @Author: zhaiyongxin
 * @Date: 2025/3/5 21:30
 * @Version: 1.0
 */
@Component
@Slf4j
public class SendMessageTaskJob {
    @Resource
    private ITaskService taskService;
    @Resource
    private IDBRouterStrategy dbRouter;
    @Resource
    private ThreadPoolExecutor executor;

    @Scheduled(cron = "0/5 * * * * ?")
    public void exec() {
        try {
            int dbCount = dbRouter.dbCount();
            for (int dbInx = 1; dbInx <= dbCount ; dbInx++) {
                int finalDbInx = dbInx;
                executor.execute(() -> {
                    try {
                        dbRouter.setDBKey(finalDbInx);
                        dbRouter.setTBKey(0);
                        List<TaskEntity> taskEntityList = taskService.queryNoSendMessageTaskList();
                        for (TaskEntity taskEntity : taskEntityList) {
                            executor.execute(() -> {
                                try {
                                    taskService.sendMessage(taskEntity);
                                    taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
                                } catch (Exception e) {
                                    log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
                                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                                }
                            });

                        }
                    } finally {
                        dbRouter.clear();
                    }
                });

            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
